package com.winona.ui;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.widget.Toast;

import com.taplinker.client.R;
import com.taplinker.core.rpc.Result;
import com.taplinker.core.util.DeviceUtil;
import com.winona.HomeActivity;
import com.winona.code.LoginCmd;
import com.winona.widget.LoadingDialog;

public class Welcome extends Activity {
	public static final String SP_FILE_NAME = "user_info";
	public static final String SP_KEY_USERNAME = "username";
	public static final String SP_KEY_PASSWORD = "password";

	private boolean toNext = true;
	private String username;
	private String password;

	private LoadingDialog mDialog;

	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.welcome);

		getLocalUserInfo();
		sleep();
	}

	private void getLocalUserInfo() {
		try {
			SharedPreferences sp = getSharedPreferences(SP_FILE_NAME,
					
					Context.MODE_PRIVATE);
			username = sp.getString(SP_KEY_USERNAME, "");
			password = sp.getString(SP_KEY_PASSWORD, "");
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private void sleep() {
		new Handler().postDelayed(new Runnable() {

			@Override
			public void run() {
				if (!toNext) {
					finish();
					return;
				}
				if (!tryAutoLogin()) {
					startActivity(new Intent(Welcome.this, LoginActivity.class));
					finish();
				}
			}
		}, 1500);
	}

	private boolean tryAutoLogin() {
		if (!DeviceUtil.isNetworkAvailable(getApplicationContext())) {
			Toast.makeText(this, "当前网络不可用", Toast.LENGTH_SHORT).show();
			return false;
		}
		if (TextUtils.isEmpty(username) || TextUtils.isEmpty(password)) {
			return false;
		}
		mDialog = new LoadingDialog(this);
		mDialog.setText("自动登录中...");
		mDialog.show();
		new LoginCmd(this, mDialog, username, password, true) {

			@Override
			public void no(Result result) {
				Toast.makeText(super.context, "自动登录失败", Toast.LENGTH_SHORT)
						.show();
				mDialog.dismiss();
				startActivity(new Intent(Welcome.this, HomeActivity.class));
				finish();
			}

		}.execute();
		return true;
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			toNext = false;
		}
		return super.onKeyDown(keyCode, event);
	}
}
